<template>
  <div>
    <my-header title="GoodsList案例"></my-header>
    <my-table style="margin-top: 45px" :goods="list">
      <template #title>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template v-slot:body="scope">
        <td>{{ scope.row.id }}</td>
        <td>{{ scope.row.goods_name }}</td>
        <td>{{ scope.row.goods_price }}</td>
        <td>
          <input
            class="tag-input form-control"
            style="width: 100px"
            type="text"
            v-if="scope.row.inputVisible"
            v-focus
            @blur="scope.row.inputVisible = false"
            v-model.trim="scope.row.inputValue"
            @keydown.enter="enterFn(scope.row)"
            @keydown.esc="scope.row.inputValue = ''"
          />
          <button
            v-else
            style="display: block"
            class="btn btn-primary btn-sm add-tag"
            @click="scope.row.inputVisible = true"
          >
            +Tag
          </button>
          <span
            v-for="(item, index) in scope.row.tags"
            :key="index"
            class="badge bg-warning text-dark"
            >{{ item }}</span
          >
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="del(scope.row.id)">
            删除
          </button>
        </td>
      </template>
    </my-table>
  </div>
</template>

<script>
import MyTable from "./components/MyTable.vue";
import MyHeader from "./components/MyHeader.vue";
export default {
  components: { MyTable, MyHeader },
  data() {
    return {
      list: [],
    };
  },
  methods: {
    async getGoods() {
      const { data: res } = await this.$http({
        method: "get",
        url: "/api/goods",
      });
      this.list = res.data;
    },
    del(id) {
      console.log(id);
      if (confirm("确定要删除吗")) {
        this.list = res.list.filter((item) => item.id !== id);
      }
    },
    enterFn(obj) {
      // 回车
      // console.log(obj.inputValue);
      if (obj.inputValue.length === 0) {
        alert("请输入数据");
        return;
      }
      obj.tags.push(obj.inputValue); // 表单里的字符串状态tags数组
      obj.inputValue = "";
    },
  },

  created() {
    this.getGoods();
  },
};
</script>

<style scoped></style>
